CtgCatalogo = function(){
	var currentCatalog;
	return {
		getCurrentCatalog: function(){return currentCatalog;},
		confirmProcess: function(option, ctgCatalogoId, ctgCatalogoActivo){
			Asg.Message.confirm(
					option == "delete" ? Asg.constants.CONFIRM_DELETE_MESSAGE :
						(ctgCatalogoActivo == "1" ? Asg.constants.CONFIRM_INACTIVATE_MESSAGE : Asg.constants.CONFIRM_ACTIVATE_MESSAGE), function(btn){
				if(btn != "no") CtgCatalogo.processRegister(option, ctgCatalogoId, ctgCatalogoActivo);
			});
		},
		processRegister: function(option, ctgCatalogoId, ctgCatalogoActivo){
			Asg.Message.progress("Guardarndo Informaci\u00F3n...");
			Ext.Ajax.request({
				timeout: Asg.constants.TIMEOUT_SECONDS,
				url: option == "delete" ? Asg.constants.CONTEXT_PATH + "/admin/catalogos/delete" : Asg.constants.CONTEXT_PATH + "/admin/catalogos/toggle",
				params: {ctgCatalogoId: ctgCatalogoId, ctgCatalogoActivo: ctgCatalogoActivo, ctgCatalogoPadre: CtgCatalogo.getCurrentCatalog()},
				callback: function(options, success, response){
					Ext.Msg.hide();
					var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
					if(!success || !jsonObject){
						Asg.Message.alertInvalid(Asg.constants.DEFAULT_ERROR_MESSAGE);
						return
					}
					Asg.Message.alert(jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE);
					if(jsonObject.success){
						if(jsonObject.data) 
							Asg.Grid.loadData("ctgCatalogoGrid", jsonObject.data);
						return;
					}
				}
			});
		},
		saveOrUpdate: function(){
			var records = Ext.getCmp("ctgCatalogoGrid").getStore().data.filterBy(function(item){return item.dirty === true && item.isValid();}).items;
			if((!records || records.length == 0) && (!newRecords || newRecords.length == 0)){
				Asg.Message.alertInvalidFields("* No se encontraron registros nuevos, ni actualizados");
				return;
			}
			var jsonString = "";
			Ext.each(records, function(record){
				jsonString += (Ext.isEmpty(jsonString) ? "" : ",") + Ext.encode(record.data);
			});
			jsonString = "[" + jsonString + "]";
			Asg.Message.progress("Guardarndo Informaci\u00F3n...");
			Ext.Ajax.request({
				timeout: Asg.constants.TIMEOUT_SECONDS,
				url: Asg.constants.CONTEXT_PATH + "/admin/catalogos/saveOrUpdateAll",
				params: {jsonString: jsonString, ctgCatalogoPadre: CtgCatalogo.getCurrentCatalog()},
				callback: function(options, success, response){
					Ext.Msg.hide();
					var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
					if(!success || !jsonObject){
						Asg.Message.alertInvalid(Asg.constants.DEFAULT_ERROR_MESSAGE);
						return
					}
					Asg.Message.alert(jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE);
					if(jsonObject.success){
						if(jsonObject.data) 
							Asg.Grid.loadData("ctgCatalogoGrid", jsonObject.data);
					}
				}
			});
		},
		initConfig: function(config){
			currentCatalog = config.ctgCatalogoPadre;
			Ext.define('ctgCatalogoModel', {
			    extend: 'Ext.data.Model',
			    idProperty: "ctgCatalogoId",
			    fields: [
			          {name: "ctgCatalogoId", type: "int"}, 
			          {name: "ctgCatalogoNombre", type: "string"}, 
		        	  {name: "ctgCatalogoPadre", type: "string", defaultValue: config.ctgCatalogoPadre},
		        	  {name: "ctgCatalogoHijo", type: "string"},
	        		  {name: "ctgCatalogoActivo", type: "string", defaultValue: "1"}
		        ]
			});
			return {
				items: {
					xtype: "grid",
					id: "ctgCatalogoGrid",
					margins: "5 5 5 5",
					flex: 1,
					store: new Ext.data.Store({
						data: config.data || [],
						model: "ctgCatalogoModel",
				        proxy: {
				            type: "memory",
				            reader: {
				                type: "array"
				            }
				        }
					}),
					columns: [
				        {
				        	header: "Nombre", 
				        	dataIndex: "ctgCatalogoNombre", 
				        	flex: 1, 
				        	minWidth: 200,
				        	field: {
				        		xtype: "textfield",
				        		enforceMaxLength: true,
				        		maxLength: 100,
				        		allowBlank: false
		        			}
			        	},{
			        		header: "Estado", 
			        		dataIndex: "ctgCatalogoActivo", 
			        		renderer: "webToActive", 
			        		width: 100,
			        		field: {
			        			xtype: "combo",
			        			store: new Ext.data.SimpleStore({
			        				data: Asg.Combo.activeInactiveArray() || [],
			        				fields: ["id", "value"]
			        			}),
			        			displayField: "value",
			        			valueField: "id",
		        				typeAhead: true,
		        				minChars: 1,
		        				queryMode: "local",
		        				forceSelection: true,
		        				triggerAction: "all"
	        				}
		        		},
		        		{
	        	        	xtype:"actioncolumn",
	        	        	align: "center",
	        	        	width: 60,
        	            	items: [
    	            	        {
		    	            		icon: Asg.constants.CONTEXT_PATH + "/resources/images/enableDisable.png",
		    	            		iconCls: "icon",
		    	            		tooltip: "Activar / Inactivar", 
		    	            		handler: function(grid, rowIndex, colIndex) {
		    	                        var record = grid.getStore().getAt(rowIndex);
		    	                        var ctgCatalogoId = record.get("ctgCatalogoId");
		    	                        if(record){
		    	                        	if(Ext.isEmpty(ctgCatalogoId) || ctgCatalogoId < 1){
	        	                        		Asg.Message.alertInvalid("Registro debe ser guardado primero para realizar esta operaci\u00F3n");
	        	                        		return;
	        	                        	}
		    	                        	CtgCatalogo.confirmProcess("toggle", record.get("ctgCatalogoId"), record.get("ctgCatalogoActivo"));
		    	                        }
		    	            		}
		            			},{
		    	            		icon: Asg.constants.CONTEXT_PATH + "/resources/images/delete.png",
		    	            		iconCls: "icon",
		    	            		tooltip: "Eliminar",
		    	            		handler: function(grid, rowIndex, colIndex) {
		    	                        var record = grid.getStore().getAt(rowIndex);
		    	                        if(record){
		    	                        	var ctgCatalogoId = record.get("ctgCatalogoId");
		    	                        	if(Ext.isEmpty(ctgCatalogoId) || ctgCatalogoId < 1){
	        	                        		grid.getStore().remove(record);
	        	                        		return;
	        	                        	}
		    	                        	CtgCatalogo.confirmProcess("delete", ctgCatalogoId, record.get("ctgCatalogoActivo"));
		    	                        }
		    	            		}
		            			}
	            			]
		        		}
		            ],
		            selType: 'cellmodel',
		            plugins: [
		                Ext.create('Ext.grid.plugin.CellEditing', {
		                    clicksToEdit: 1
		                })
		            ],
					tbar: [
	        	       "->",
	        	       {
	        	    	   text: "Agregar", 
	        	    	   iconCls: Asg.constants.ADD_ICON,
	        	    	   handler: function(){
	        	    		   Ext.getCmp("ctgCatalogoGrid").getStore().insert(0, ctgCatalogoModel.create());
	        	    		   Ext.getCmp("ctgCatalogoGrid").editingPlugin.startEditByPosition({row: 0, column: 0});
	        	    	   }
        	    	   },
	        	       "-",
	        	       {text: "Guardar", iconCls: Asg.constants.SAVE_ICON, handler: CtgCatalogo.saveOrUpdate}
        	        ]
				}
			};
		}
	};
}();